package com.upu173.music.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;

import com.andbase.library.utils.AbLogUtil;
import com.andbase.library.utils.AbStrUtil;
import com.upu173.music.global.PlayerData;
import com.upu173.music.model.PlayList;
import com.upu173.music.service.MusicPlayerService;


public class PlayerManagerReceiver  extends BroadcastReceiver {

    public static final String ACTION_MUSIC_PLAYER = "android.intent.action.MUSIC_PLAYER";
    private Context context;
    private MediaPlayer mediaPlayer  = null;
    public boolean isStopMp = false;
    public boolean isStopAs = false;
    public String filePath = null;


    public static final String MESSAGE_KEY = "MESSAGE_KEY";
    public static final int MESSAGE_INIT = 0;
    public static final int MESSAGE_PLAY = 1;
    public static final int MESSAGE_PAUSE = 2;
    public static final int MESSAGE_STOP = 3;
    public static final int MESSAGE_SEEKTO = 4;
    public static final int MESSAGE_RELEASE = 9;

    public static final String EXTRA_VALUE_SEEKTO = "EXTRA_KEY_SEEKTO";
    public static final String EXTRA_VALUE_PATH = "EXTRA_VALUE_PATH";


    private Handler handlerSeekBar = new Handler();
    private Runnable runnableSeekBar = new Runnable() {
        @Override
        public void run() {

            int currentTime = MusicPlayerService.playerManagerReceiver.getCurrentPosition();
            AbLogUtil.i("PlayerManagerReceiver","CurrentPosition:" + currentTime);
            AbLogUtil.i("PlayerManagerReceiver","Duration:" + MusicPlayerService.playerManagerReceiver.getDuration());
            AbLogUtil.i("PlayerManagerReceiver","剩余:" + (MusicPlayerService.playerManagerReceiver.getDuration() - currentTime)/1000 + "s");
            if(currentTime == 0 || currentTime <=  MusicPlayerService.playerManagerReceiver.getDuration() - 3000){
                handlerSeekBar.postDelayed(this,500);
            }else{
                nextSong();
            }

        }
    };


    public PlayerManagerReceiver() {
    }

    public PlayerManagerReceiver(Context context) {
        super();
        this.context = context;
        initMediaPlayer();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int message = intent.getIntExtra(MESSAGE_KEY,MESSAGE_INIT);
        switch (message) {
            case MESSAGE_INIT:
                AbLogUtil.i("PlayerManagerReceiver","init MediaPlayer");
                break;
            case MESSAGE_RELEASE:
                AbLogUtil.i("PlayerManagerReceiver","release MediaPlayer");
                release();
                break;
            case MESSAGE_PLAY:
                String path = intent.getStringExtra(EXTRA_VALUE_PATH);
                if(AbStrUtil.isEmpty(path)){
                    startPlay(0,false);
                }else{
                    stopPlay();
                    initFileDescriptor(path);
                    startPlay(0,true);

                }

                break;
            case MESSAGE_PAUSE:
                pausePlay();
                break;
            case MESSAGE_STOP:
                stopPlay();
                break;
            case MESSAGE_SEEKTO:
                int msec = intent.getIntExtra(EXTRA_VALUE_SEEKTO,0);
                seekTo(msec);
                break;
        }

    }

    public void initFileDescriptor(String path){
        try {
            if(path!= null){
                filePath = path;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
    }

    public int getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }

    public int getDuration() {
        return mediaPlayer.getDuration();
    }

    public boolean isPlaying(){
        if(mediaPlayer.isPlaying()){
            return true;
        }
        return false;
    }


    public void  startPlay(final int position,boolean restart){
        try {

            handlerSeekBar.removeCallbacks(runnableSeekBar);

            if(restart || isStopMp){
                mediaPlayer.reset();
                AbLogUtil.i("PlayerManagerReceiver","普通播放：" + filePath);
                mediaPlayer.setDataSource(filePath);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        AbLogUtil.i("PlayerManagerReceiver","start MediaPlayer new");
                        mediaPlayer.start();
                    }
                });
                mediaPlayer.prepareAsync();
            }else{

                if(!mediaPlayer.isPlaying()){
                    if(position > 0){
                        seekTo(position);
                    }
                    AbLogUtil.i("PlayerManagerReceiver","start MediaPlayer resume");
                    mediaPlayer.start();
                }
            }
            isStopMp = false;


            handlerSeekBar.postDelayed(runnableSeekBar,200);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void nextSong(){

        PlayList playSong = PlayerData.getNextPlaySong();
        if(playSong!=null){
            stopPlay();
            initFileDescriptor(playSong.getPath());
            PlayerData.setCurrentPlaySong(PlayerData.position + 1);
            startPlay(0,true);
        }

    }

    public void  pausePlay(){
        handlerSeekBar.removeCallbacks(runnableSeekBar);
        AbLogUtil.i("PlayerManagerReceiver", "pause MediaPlayer");
        mediaPlayer.pause();
    }

    public void  stopPlay(){
        handlerSeekBar.removeCallbacks(runnableSeekBar);
        AbLogUtil.i("PlayerManagerReceiver","stop MediaPlayer");
        mediaPlayer.stop();
        isStopAs = true;
        isStopMp = true;
    }

    public void seekTo(int currentTime) {
        AbLogUtil.i("PlayerManagerReceiver","seekTo:" + currentTime);
        mediaPlayer.seekTo(currentTime);
    }


    public void release() {
        try{
            if(mediaPlayer != null){
                mediaPlayer.stop();
                mediaPlayer.release();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
